import {Card, Breadcrumb, Form, Button, Radio, Input, Upload, Space, Select, message} from 'antd';
import {PlusOutlined} from '@ant-design/icons';
import {Link, useNavigate,useSearchParams} from 'react-router-dom';
import {useState, useEffect, useRef} from 'react';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

import './index.scss';
import {http} from '@/utils';

const {Option} = Select;

export default function Publish() {
	// 获取文章id
	const [params] = useSearchParams();
	const articleId = params.get('id');
	// 获取频道列表
	const [channels, setChannels] = useState([]);
	// 上传图片列表
	const [fileList, setFileList] = useState([]);
	// 上传图片类型
	const [imgCount, setImgCount] = useState(1);
	// 获取from实例
	const form = useRef(null);
	// 路由跳转
	const navigate=useNavigate()

	// 组件载在完成后获取频道数据
	useEffect(() => {
		http.get('/channels').then(res => {
			setChannels(res.data.channels);
		});
	}, []);

	// 上传图片
	function onUploadChange(info) {
		// 获取图片地址列表
		const fileList = info.fileList.map(file => {
			if (file.response) {
				return {
					url: file.response.data.url,
				};
			}
			return file;
		});
		setFileList(fileList);
	}

	// 修改上传类型
	function changeType(e) {
		setImgCount(e.target.value);
		// 清空上传图片
		setFileList([]);
	}

	// 发布或者修改
	function onFinish(values) {
		// 获取参数
		const {channel_id, content, title, type} = values;
		const params = {
			channel_id,
			content,
			title,
			cover: {
				type: type,
				images: fileList.map(item => item.url),
			},
		};
		if (articleId) {
			// 修改文章
			http.put(`/mp/articles/${articleId}?draft=false`, params).then(res => {
				message.success('修改成功');
			});
		} else {
			// 发布文章
			http.post('/mp/articles?draft=false', params).then(res => {
				message.success('发布成功');
			});
		}
		navigate("/layout/article")
	}

	// 修改获取当前文章
	useEffect(() => {
		if (articleId) {
			// 拉取数据回显
			http.get(`/mp/articles/${articleId}`).then(res => {
				const {cover, ...formValue} = res.data;
				// 动态设置表单数据
				form.current.setFieldsValue({...formValue, type: cover.type});
				// 重置图片选择类型
				setImgCount(cover.type)
				// 格式化封面图片数据
				const imageList = cover.images.map(url => ({url}));
				setFileList(imageList);
			});
		} else {
			form.current.resetFields();
			// 清空上传图片
			setFileList([]);
		}
	}, [articleId]);

	return (
		<div className="publish">
			<Card
				title={
					<Breadcrumb separator=">">
						<Breadcrumb.Item>
							<Link to="/home">首页</Link>
						</Breadcrumb.Item>
						<Breadcrumb.Item>{articleId ? '修改文章' : '发布文章'}</Breadcrumb.Item>
					</Breadcrumb>
				}>
				<Form
					labelCol={{span: 4}}
					wrapperCol={{span: 16}}
					initialValues={{type: 1, content: ''}}
					onFinish={onFinish}
					ref={form}>
					<Form.Item
						label="标题"
						name="title"
						rules={[{required: true, message: '请输入文章标题'}]}>
						<Input placeholder="请输入文章标题" style={{width: 400}} />
					</Form.Item>
					<Form.Item
						label="频道"
						name="channel_id"
						rules={[{required: true, message: '请选择文章频道'}]}>
						<Select placeholder="请选择文章频道" style={{width: 400}}>
							{channels.map(item => (
								<Option key={item.id} value={item.id}>
									{item.name}
								</Option>
							))}
						</Select>
					</Form.Item>

					<Form.Item label="封面">
						<Form.Item name="type">
							<Radio.Group onChange={changeType}>
								<Radio value={1}>图片</Radio>
								<Radio value={0}>无图</Radio>
							</Radio.Group>
						</Form.Item>
						<Upload
							name="image"
							listType="picture-card"
							className="avatar-uploader"
							showUploadList
							action="http://geek.itheima.net/v1_0/upload"
							fileList={fileList}
							onChange={onUploadChange}
							maxCount={1}
							disabled={imgCount === 0}>
							<div style={{marginTop: 8}}>
								<PlusOutlined />
							</div>
						</Upload>
					</Form.Item>

					<Form.Item
						label="内容"
						name="content"
						rules={[{required: true, message: '请输入文章内容'}]}>
						<ReactQuill
							className="publish-quill"
							theme="snow"
							placeholder='请输入文章内容'
						/>
					</Form.Item>

					<Form.Item wrapperCol={{offset: 4}}>
						<Space>
							<Button size="large" type="primary" htmlType="submit">
								{articleId ? '修改文章' : '发布文章'}
							</Button>
						</Space>
					</Form.Item>
				</Form>
			</Card>
		</div>
	);
}
